package com.kzd.btgame.main.home

import android.Manifest
import android.content.Intent
import android.text.Editable
import android.view.LayoutInflater
import androidx.lifecycle.LifecycleOwner
import com.kzd.btgame.R
import com.kzd.btgame.custom.setOnClickAntiShakeListener
import com.kzd.btgame.databinding.ActivityBargainSellBinding
import com.kzd.btgame.entity.GamePlayed
import com.kzd.btgame.entity.GameSmall
import com.kzd.btgame.jetpack.vm.BargainViewModel
import com.kzd.btgame.main.home.adapter.ImageSelectAdapter
import com.kzd.btgame.main.popup.GameBargainPopup
import com.kzd.btgame.main.popup.LoadingDialog
import com.module.lemlin.app.OwnerStatusBar
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import java.lang.StringBuilder

class BargainSellActivity : OwnerViewBindingActivity<ActivityBargainSellBinding>() {

    private var mGamePlayed: GamePlayed? = null
    private var mGameSmall: GameSmall? = null
    private var mImages: MutableList<String> = mutableListOf()

    private val mGameBargainPopup: GameBargainPopup by lazy {
        GameBargainPopup(context = this, onGamePlayed = { _, gamePlayed ->
            mGameBargainPopup.dismiss()
            this.mGamePlayed = gamePlayed
            mViewBinding.tvBargainSellGame.text = gamePlayed.name
            mViewBinding.tvBargainSellSmall.text = null
            mViewBinding.etBargainSellArea.text = null
        }, onGameSmall = { _, gameSmall ->
            mGameBargainPopup.dismiss()
            this.mGameSmall = gameSmall
            mViewBinding.tvBargainSellSmall.text = gameSmall.user_name
            mViewBinding.etBargainSellArea.text =
                Editable.Factory.getInstance().newEditable(gameSmall.server_name)
        })
    }

    private val mImageSelectAdapter = ImageSelectAdapter()

    private val mViewModel: BargainViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityBargainSellBinding
        get() = ActivityBargainSellBinding::inflate

    override fun initStatusBar(statusBar: OwnerStatusBar) {
        statusBar.run {
            addView = mViewBinding.flBargainSellBar
            barColor = R.color.white
        }
        super.initStatusBar(statusBar)
    }

    override fun initView() {

        mViewBinding.rvBargainSellBody.adapter = mImageSelectAdapter.apply {
            setNewInstance(mutableListOf(R.mipmap.photo_add_icon))
        }
        mImageSelectAdapter.setOnItemClickListener { _, _, position ->
            if (position != 0) {
                return@setOnItemClickListener
            }
            requestDangerousPermissions(arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            ), requestCode = 1)
        }

        mViewBinding.tvBargainSellGame.setOnClickAntiShakeListener {
            mViewModel.bargainGame()
        }
        mViewBinding.tvBargainSellSmall.setOnClickAntiShakeListener {
            if (mGamePlayed == null) {
                toast("请选择游戏")
            } else mGamePlayed?.let {
                mViewModel.bargainGameSmall(it.id, it.appid)
            }
        }
        mViewBinding.tvBargainSellSubmit.setOnClickAntiShakeListener {
            when {
                mGamePlayed == null -> toast("请选择游戏")
                mGameSmall == null -> toast("请选择小号")
                mViewBinding.etBargainSellArea.text.isNullOrEmpty() -> toast("请填写游戏区服")
                mViewBinding.etBargainSellPrice.text.isNullOrEmpty() -> toast("请填写出售价格")
                mViewBinding.etBargainSellTitle.text.isNullOrEmpty() -> toast("请填写标题")
                mViewBinding.etBargainSellDesc.text.isNullOrEmpty() -> toast("请填写商品描述")
                mImages.isNullOrEmpty() -> toast("请选择图片")
                else -> mViewModel.userUpload(images = mImages)
            }
        }
    }

    override fun initData() {

    }

    override fun initViewMode() {
        mViewModel.gamePlayedLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            mGameBargainPopup.fillDataGamePlayed(data)
                .showPopupWindow()
        })
        mViewModel.gameSmallLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            mGameBargainPopup.fillDataGameSmall(data)
                .showPopupWindow()
        })

        mViewModel.userUploadLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(context = this, resId = R.layout.dialog_load_style_1)
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            if (data.size == 0)
                return@observe
            val images = StringBuilder()
            data.forEach {
                images.append(it).append(",")
            }
            mViewModel.bargainSubmit(
                name = mViewBinding.etBargainSellTitle.text.toString(),
                game_id = mGamePlayed?.id ?: "",
                introduction = mViewBinding.etBargainSellDesc.text.toString(),
                sname = mViewBinding.etBargainSellArea.text.toString(),
                small_id = mGameSmall?.small_id ?: "",
                two_passwd = mViewBinding.etBargainSellPwd.text.toString(),
                money = mViewBinding.etBargainSellPrice.text.toString(),
                system = "1",
                images = images.substring(0, images.length - 1).toString()
            )
        })

        mViewModel.bargainSubmitLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS)
                return@observe
            LoadingDialog.dismiss()
            toast(response.data?.message)
            finish()
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            val images: MutableList<Any> = mutableListOf()
            images.add(R.mipmap.photo_add_icon)
            pathList.forEach {
                images.add(it)
            }
            mImageSelectAdapter.setNewInstance(images)
            mImages.clear()
            mImages.addAll(pathList)
        }
    }

    override fun handlePermissionResult(requestCode: Int, granted: Boolean): Boolean {
        if (!granted) {
            toast("请到应用设置中开启存储权限！")
            return false
        }
        if (requestCode == 1) {
            mViewModel.userMatisse(activity = this, maxSelectable = 7)
        }
        return super.handlePermissionResult(requestCode, granted)
    }

}